<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member\user;

use buwang\base\MemberBaseController;
use buwang\util\CommonTool;
use jianyan\excel\Excel;
use think\facade\Db;
use think\facade\View;
use app\manage\model\User;
use app\common\model\MemberMiniapp;

/**
 * @ControllerAnnotation(title="用户提现记录表")
 */
class ExtractLog extends MemberBaseController
{
    use \buwang\traits\Crud;

    protected $relationSearch = true;

    public function initialize()
    {
        parent::initialize();
        $this->layout && $this->app->view->engine()->layout($this->layout);
        $this->model = new \app\common\model\UserExtractLog();

        $this->assign('getUserList', $this->model->getUserList());

        $this->assign('getExtractTypeList', $this->model->getExtractTypeList());

        $this->assign('getTypeList', $this->model->getTypeList());

        $this->assign('getStatusList', $this->model->getStatusList());

    }


    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            //查询该租户的所有应用
            $ids = MemberMiniapp::where('member_id', $this->user->top_id)->column('id');
            if (!$ids) return $this->success('success', ['total' => 0, 'list' => []]);

            $count = $this->model
                ->withJoin('user', 'LEFT')
                ->where($where)
                ->where('user.member_miniapp_id', 'in', $ids)
                ->count();
            $list = $this->model
                ->withJoin('user', 'LEFT')
                ->where($where)
                ->where('user.member_miniapp_id', 'in', $ids)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'total' => $count,
                'list' => $list,
            ];
            return $this->success('success', $data);
        }
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        $row->isEmpty() && $this->error('数据不存在');
        //得到提现用户
         $user = User::find($row['user_id']);
         if(!$user)$this->error('提现用户不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $post = reform_keys($post);
            $rule = [];
            $this->validate($post, $rule);
            $extractStatus = 0;
            try {
                //提现失败退款
                if ($post['status'] == '-1') {
                    if ($row['return_price'] < $row['extract_price']) {
                        $price = $row['extract_price'];
                        $fail_msg = $post['fail_msg'];
                        $price = bcsub($price, $row['return_price'], 2);
                        if ($price > 0) {
                            User::changeMoney($row['user_id'], $price, $memoContent = '提现失败退款', 'extract_add', "提现失败退还余额{$price}元，{$fail_msg}", $row['id']);
                            $extractStatus = 2;
                          }
                        }
                        $sum = bcadd($price, $row['return_price'], 2);
                        if ($sum > $price) $sum = $price;
                        $post['return_price'] = $sum;
                    }
                    if($post['status'] == '1'&&$post['status']!=$row['status']){
                        $extractStatus = 1;
                    }

                $save = $row->save($post);
                    if($extractStatus==1){
                        //提现成功
                        event('UserExtractSuccess',[$user,$row]);
                    }elseif ($extractStatus==2){
                        //提现失败
                        event('UserExtractFail',[$user,$row,$fail_msg]);
                    }

            } catch (\Exception $e) {
                return $this->error('保存失败');
            }
            if (!$save) return $this->error('保存失败');
            return $this->success('保存成功');
        }
        View::assign('row', $row);
        return view();
    }
}